package intranet.controllers;
import org.springframework.web.servlet.ModelAndView;

import intranet.addon.Encryption;
import intranet.models.*;
import intranet.tools.*;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sun.mail.iap.Response;

@Controller
public class UserController extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/* IsNumber Function */
	public static boolean IsNumber(String num) {
        try {
            Integer.parseInt(num);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	@RequestMapping("/login.html")
	public ModelAndView Login(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
    ResultSet rs=null;
	String user_name=request.getParameter("username");
	String pwd=request.getParameter("password");
	ModelAndView mv=new ModelAndView("Login");;
	RegistrationModel rm=new RegistrationModel();
	LoginModel lm=new LoginModel();
    HttpSession session = request.getSession();
    String error="";
    String pass=null;
	if(user_name!=null){
		error="Incorrect User ID or Password. Please try again.";
		pass=Encryption.encodePassword(pwd, "MD5");
		if(lm.verifyUser(user_name, pass)){
	        session.setAttribute("user_id",lm.getUserIdByUserName(user_name));
	        session.setAttribute("user_name",user_name);
	        response.sendRedirect("home.html");
		}else{
		    mv.addObject("error",error);
		}
	}
	return mv;
		
	}	
		@RequestMapping("/logout.html")
		public void Logout1(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
		    HttpSession session = request.getSession();
		    session.removeAttribute("user_id");
		    session.removeAttribute("user_name");
			response.sendRedirect("login.html");
		}
		//Registration.html
		@RequestMapping("/register.html")
		public ModelAndView Registration(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
			RegistrationModel rm=new RegistrationModel();
			String fullname=request.getParameter("fullname");
			String userid=request.getParameter("userid");
			String mail=request.getParameter("mail");
			String dpt=request.getParameter("dpt");
			String pwd=request.getParameter("password");
			String password="";
			String uid="abc";
			ModelAndView mv=new ModelAndView("Registration");
			ResultSet rsx =rm.SelectUser();	
			if(pwd!=null)
				password = Encryption.encodePassword(pwd,"MD5");
			while(rsx.next())
			uid=uid+"|"+rsx.getString("USER_NAME");
			ResultSet rs=rm.SelectDepartment();
			ArrayList dpm=this.resultSetToArrayList(rs);
			mv.addObject("dpm",dpm);
			mv.addObject("user",uid+"|");
			if(userid!=null){
		        rm.AddUser(fullname, userid, password, mail,dpt,pwd);
		        response.sendRedirect("sendmail.html?NBCMail="+mail+"&code="+password+"");
				//response.sendRedirect("mail.html?NBCMail="+mail+"&code="+password+"");
		        	
			}
			return mv;
		}
		
	@RequestMapping("/mail.html")
	public ModelAndView mail(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
		String mail=request.getParameter("NBCMail");
		String password=request.getParameter("code");
		ModelAndView mv=new ModelAndView("index");
		response.sendRedirect("Sendmail?NBCMail="+mail+"&code="+password+"");
		return mv;
	}

	@RequestMapping("/activate_account.html")
public ModelAndView SendMail(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
	//response.sendRedirect("Sendmail");	
	RegistrationModel rm=new RegistrationModel();
	String code=request.getParameter("code");
	String to=request.getParameter("mail");
	rm.Activation(code,to);
	//mv.addObject("includethispage", "activation.jsp");
	WebConfig conf=new WebConfig();
	String BaseUrl=conf.getURL();
	String LoginUrl=BaseUrl+"login.html";
	ModelAndView mv=new ModelAndView("activation");
	mv.addObject("loginurl",LoginUrl);
	mv.addObject("code",code);
	return mv;
}
@RequestMapping("/CompleteRegistration.html")
public ModelAndView registration(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
	//RegistrationModel rm=new RegistrationModel();
	String mail=request.getParameter("email");
	ModelAndView mv=new ModelAndView("CompleteRegistration");
	//mv.addObject("includethispage", "CompleteRegistration.jsp");
	mv.addObject("mail",mail);
	return mv;
}	

//forgetpassword
 @RequestMapping("/resets.html")
	public ModelAndView forgetpassword(HttpServletRequest request, HttpServletResponse response) throws SQLException, IOException{		
	RegistrationModel rm=new RegistrationModel();
	//String email=request.getParameter("email");
	String email="da.born@nbc.org.kh";
	String res=null;
	String mail=null;
	ModelAndView mv=new ModelAndView("index");
	//if(email==null){
	//mv.addObject("includethispage", "resetpassword.jsp");
	//mv.addObject("email",email);
	//return mv;
	//}
	if(email!=null){
		ResultSet rsx =rm.SelectReset();
			while(rsx.next())
				if(rsx.getString("NBC_EMAIL").equalsIgnoreCase(email)){
					mail=rsx.getString("NBC_EMAIL");
					res=rsx.getString("TEMPMAIL");
					mv.addObject("includethispage", "reset_success.jsp");
					mv.addObject("email",email);
			//	    response.sendRedirect("ResetMail?NBCMail="+mail+"&reset="+res+"");
					response.sendRedirect("Mail");
					return mv;	
		}
	}
	return mv;
 }	
	 
	// RESULTSET TO ARRAYLIST
	   public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
		    ResultSetMetaData md = rs.getMetaData();
		    int columns = md.getColumnCount();
		    ArrayList results = new ArrayList();
		    while (rs.next()){
		    HashMap row = new HashMap();
		    results.add(row);
		    for(int i=1; i<=columns; i++){
		    row.put(md.getColumnName(i),rs.getObject(i));
		    }
		    }
		    return results;

	    }
	  
}